<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!--alert警告  -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cate_goods">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedParams"
            :options="cateGoodsList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="addGoods"
            >添加参数</el-button
          >
          <!-- 动态参数的table -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开航 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="item in scope.row.attr_vals"
                  closable
                  :key="item"
                  @close="handleClose(item, scope.row.attr_vals)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row.attr_vals)"
                  @blur="handleInputConfirm(scope.row.attr_vals)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >添加</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column prop="attr_name" label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeClick(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="addGoods"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开航 -->
            <el-table-column type="expand"></el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column prop="attr_name" label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeClick(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加按钮 对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 对话框表单验证 -->
      <el-form
        :model="ruleForm"
        :rules="addGoodRules"
        ref="goodRuleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 对话框表单验证 -->
      <el-form
        :model="editruleForm"
        :rules="editGoodRules"
        ref="editGoodRuleForm"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除弹框 -->
  </div>
</template>

<script>
import {
  getGoods,
  getParamsId,
  getAddParams,
  getEditParams,
  getEdit,
  getDeleteParams
} from '@/network/goods_params.js'
export default {
  name: 'Params',
  data() {
    return {
      // 所有分类
      cateGoodsList: [],
      //   级联选择框
      cateProps: {
        expandTrigger: 'hover',
        checkStrictlyL: 'true',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   id双向绑定的v-model  级联选择框
      selectedParams: [],
      //   tab页签默人选择
      activeName: 'many',
      //   获取面板数据参数
      paramsQuery: {
        id: null,
        sel: ''
      },
      //   所有动态参数
      manyTabData: [],
      //   所有的静态属性
      onlyTabData: [],
      //   控制添加对话框显示和隐藏
      addDialogVisible: false,
      // 添加对话框显示和隐藏
      editDialogVisible: false,
      // 添加对话框 表单数据对象
      ruleForm: {
        attr_name: ''
      },
      // 修改对话框 表单数据对象
      editruleForm: {},
      inputVisible: false,
      inputValue: '',

      // 表单验证规则
      addGoodRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 编辑表单验证规则
      editGoodRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    //   获取所有分类数据
    async getGoods() {
      const { data: res } = await getGoods()
      this.$message.success('成功了')
      this.cateGoodsList = res.data
    },
    // 当级联选择器发生改变 触发的回调
    handleChange() {
      if (this.selectedParams.length !== 3) {
        this.selectedParams = []
      }
      this.handleTabClick()
    },
    // tab页签点击事件
    handleTabClick() {
      //   根据所选分类id 和面板获取对应的参数
      this.paramsQuery.id = this.cateId
      this.paramsQuery.sel = this.activeName
      getParamsId(this.paramsQuery).then(({ data: res }) => {
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : ''
          console.log(item.attr_vals)
        })

        this.$message.success('获取成功')
        if (this.activeName === 'many') {
          this.manyTabData = res.data
        } else {
          this.onlyTabData = res.data
        }
      })
    },
    // 添加属性点击监听
    addGoods() {
      this.addDialogVisible = true
    },
    // 关闭添加属性对话框 并清除
    addDialogClose() {
      this.$refs.goodRuleForm.resetFields()
    },
    // 点击确定请求数据
    addParams() {
      this.$refs.goodRuleForm.validate((val) => {
        if (!val) {
          return this.$message.error('请检查表单数据')
        }
        getAddParams(this.paramsQuery, this.ruleForm).then((res) => {
          this.$message.success('添加动态参数成功')
          this.addDialogVisible = false
          this.handleTabClick()
        })
      })
    },
    // 编辑显示对话框   点击编辑 获取id 将最新的form表单中数据绑定赋值 =>
    showEditDialog(attrId) {
      this.editDialogVisible = true
      getEditParams(this.paramsQuery, this.editruleForm, attrId).then(
        ({ data: res }) => {
          this.editruleForm = res.data
          console.log(this.editruleForm)
        }
      )
    },
    // 关闭编辑对话框 重置数据
    editDialogClose() {
      this.$refs.editGoodRuleForm.resetFields()
    },
    // 点击确定修改参数
    editParams() {
      this.$refs.editGoodRuleForm.validate((val) => {
        if (!val) {
          return this.$message.error('请检查表单数据')
        }
        getEdit(this.editruleForm).then(({ data: res }) => {
          console.log(res)
          this.editDialogVisible = false
          this.handleTabClick()
        })
      })
    },
    // 删除
    removeClick(attrId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          getDeleteParams(this.paramsQuery, attrId).then(({ data: res }) => {
            this.handleTabClick()
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    handleClose(item, row) {
      row.splice(row.indexOf(item), 1)
    },
    // 添加tag 按下和失去焦点都会触发
    handleInputConfirm(attrVals) {
      const inputValue = this.inputValue
      if (inputValue) {
        attrVals.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 点击显示
    showInput(row) {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    //   按钮需要被禁用 返回true
    isBtnDisable() {
      if (this.selectedParams.length === 3) {
        return false
      }
      return true
    },
    cateId() {
      if (this.selectedParams.length === 3) {
        return this.selectedParams[this.selectedParams.length - 1]
      }
      return null
    },
    //   title text  一个计算属性 决定是添加参数还是添加属性
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  // -------------生命周期函数
  created() {
    this.getGoods()
  }
}
</script>

<style scope>
.cate_goods {
  margin: 20px 0;
  font-size: 16px;
}
.el-tag {
  margin: 5px 20px;
}
.input-new-tag {
  width: 120px;
}
</style>
